package li.wei.sentinel.sentinel.cmd;

import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.util.StringUtil;
import li.wei.sentinel.SentinelRuleConfig;
import li.wei.sentinel.sentinel.RuleManager;
import li.wei.sentinel.sentinel.SentinelRuleConst;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by liwei on 2018/8/30.
 * 一些命令，用于动态修改Sentienl规则的配置
 */
@RestController
public class SentinelController {

    static SentinelRuleConfig sentinelRuleConfig = new SentinelRuleConfig();

    @RequestMapping("/update/{rule}")
    public List updateRule(@PathVariable("rule") String rule, HttpServletRequest request){
        String countStr = request.getParameter("count");
        double count = StringUtil.isNotBlank(countStr)?Double.parseDouble(countStr): SentinelRuleConst.FLOW_QPS;
        String twStr = request.getParameter("timewindow");
        int timewindow = StringUtil.isNotBlank(twStr)?Integer.parseInt(twStr):SentinelRuleConst.DEGRADE_TIMEWINDOW;
        return sentinelRuleConfig.updateRule(rule,count,timewindow);
    }

    @RequestMapping("/show/{rule}")
    public List showRule(@PathVariable("rule") String rule){
        if(rule.equals("flow")){
            return FlowRuleManager.getRules();
        }
        if(rule.equals("degrade")){
            return DegradeRuleManager.getRules();
        }
        return null;
    }

    @RequestMapping("/set/{rule}/{state}")
    public String openRule(@PathVariable("rule") String rule,@PathVariable("state") String state){
        if(rule.equals("flow")){
            SentinelRuleConst.FLOW_OPEN = state.equals("open")?true:false;
            return "success";
        }
        if(rule.equals("degrade")){
            SentinelRuleConst.DEGRADE_OPEN = state.equals("open")?true:false;
            return "success";
        }
        return "wrong input String";
    }
}